import { useEffect,useState  } from 'react';
import styles from './index.module.scss';
import dynamic from 'next/dynamic';
import { useTheme } from 'next-themes'

// 动态导入 SyntaxHighlighter，禁用 SSR
const SyntaxHighlighter = dynamic(
  () => import('react-syntax-highlighter').then((mod) => mod.Prism),
  { ssr: false },
);

export function CodeView({ code, lang }) {
  const [themeFile, setThemeFile] = useState(null);
  const { theme } = useTheme()

  useEffect(() => {
    // 客户端环境下动态导入主题
    import('react-syntax-highlighter/dist/esm/styles/prism').then((themes) => {
      const themeMap = {
        dark: themes.vscDarkPlus,
        light: themes.coy,
      };
      setThemeFile(themeMap[theme] || themes.vscDarkPlus);
    });
  }, [theme]);

  if (!themeFile) return <div className={styles.codeCont}></div>;
  return (
    <div className={styles.codeCont}>
      <SyntaxHighlighter
        showLineNumbers={true} // 是否展示左侧行数
        lineNumberStyle={{ color: '#ddd', fontSize: 10 }} // 左侧行数的样式
        style={themeFile} // 主题风格
        language={lang || 'javascript'} // 需要语言类型 如css, jsx , javascript 等
        PreTag="div"
      >
        {code}
      </SyntaxHighlighter>
    </div>
  );
}
